package com.lexue.articlesync.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 头条号Cookies管理服务
 */
@Slf4j
@Service
public class ToutiaoCookiesService {
    
    private static final String TOUTIAO_LOGIN_URL = "https://mp.toutiao.com/login/";
    private static final String TOUTIAO_USER_INFO_URL = "https://mp.toutiao.com/mp/agw/media/get_media_info";
    private static final String TOUTIAO_HOME_URL = "https://mp.toutiao.com/profile_v3/graphic/publish";
    
    private final OkHttpClient httpClient;
    
    public ToutiaoCookiesService() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .followRedirects(true)
                .build();
    }
    
    /**
     * 检测头条网页登录状态并获取cookies
     */
    public CookiesResult detectAndGetCookies() {
        try {
            // 首先尝试检查是否已有登录状态
            Request request = new Request.Builder()
                    .url(TOUTIAO_HOME_URL)
                    .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                    .addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
                    .addHeader("Accept-Encoding", "gzip, deflate, br")
                    .build();
                    
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    
                    // 检查是否包含登录相关的内容
                    if (responseBody.contains("用户登录") || responseBody.contains("login")) {
                        return CookiesResult.notLoggedIn("未检测到头条登录状态，请先在浏览器中登录头条号");
                    }
                    
                    // 如果响应中包含用户信息，说明已登录
                    if (responseBody.contains("userInfo") || responseBody.contains("user_id")) {
                        // 从响应头中获取cookies
                        String cookies = extractCookiesFromResponse(response);
                        if (cookies != null && !cookies.isEmpty()) {
                            // 进一步验证cookies有效性
                            if (validateCookies(cookies)) {
                                return CookiesResult.success(cookies, extractUserInfo(responseBody));
                            }
                        }
                    }
                }
            }
            
            return CookiesResult.error("无法获取有效的登录cookies，请确保已在浏览器中登录头条号");
            
        } catch (Exception e) {
            log.error("检测头条登录状态失败", e);
            return CookiesResult.error("检测登录状态时发生错误: " + e.getMessage());
        }
    }
    
    /**
     * 验证cookies有效性
     */
    public boolean validateCookies(String cookies) {
        try {
            Request request = new Request.Builder()
                    .url(TOUTIAO_USER_INFO_URL)
                    .addHeader("Cookie", cookies)
                    .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .addHeader("Accept", "application/json, text/plain, */*")
                    .addHeader("Referer", "https://mp.toutiao.com/")
                    .addHeader("X-Requested-With", "XMLHttpRequest")
                    .build();
                    
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    log.debug("头条号用户信息响应: {}", responseBody);
                    
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    
                    // 检查返回的数据结构
                    if (jsonResponse != null && jsonResponse.containsKey("data")) {
                        JSONObject data = jsonResponse.getJSONObject("data");
                        if (data != null && data.containsKey("user")) {
                            JSONObject user = data.getJSONObject("user");
                            // 检查是否有用户ID，表示登录成功
                            if (user != null && user.containsKey("id")) {
                                log.info("头条号cookies验证成功，用户ID: {}", user.getString("id"));
                                return true;
                            }
                        }
                    }
                    
                    log.warn("头条号cookies验证失败，返回数据格式不正确: {}", responseBody);
                } else {
                    log.warn("头条号cookies验证失败，HTTP状态码: {}", response.code());
                }
            }
        } catch (Exception e) {
            log.error("验证cookies失败", e);
        }
        
        return false;
    }
    
    /**
     * 验证cookies有效性并返回用户信息
     */
    public CookiesValidationResult validateCookiesWithUserInfo(String cookies) {
        try {
            Request request = new Request.Builder()
                    .url(TOUTIAO_USER_INFO_URL)
                    .addHeader("Cookie", cookies)
                    .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .addHeader("Accept", "application/json, text/plain, */*")
                    .addHeader("Referer", "https://mp.toutiao.com/")
                    .addHeader("X-Requested-With", "XMLHttpRequest")
                    .build();
                    
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    log.debug("头条号用户信息响应: {}", responseBody);
                    
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    
                    // 检查返回的数据结构
                    if (jsonResponse != null && jsonResponse.containsKey("data")) {
                        JSONObject data = jsonResponse.getJSONObject("data");
                        if (data != null && data.containsKey("user")) {
                            JSONObject user = data.getJSONObject("user");
                            // 检查是否有用户ID，表示登录成功
                            if (user != null && user.containsKey("id")) {
                                log.info("头条号cookies验证成功，用户ID: {}", user.getString("id"));
                                return CookiesValidationResult.success(user);
                            }
                        }
                    }
                    
                    log.warn("头条号cookies验证失败，返回数据格式不正确: {}", responseBody);
                    return CookiesValidationResult.invalid("返回数据格式不正确");
                } else {
                    log.warn("头条号cookies验证失败，HTTP状态码: {}", response.code());
                    return CookiesValidationResult.invalid("HTTP请求失败，状态码: " + response.code());
                }
            }
        } catch (Exception e) {
            log.error("验证cookies失败", e);
            return CookiesValidationResult.error("验证异常: " + e.getMessage());
        }
    }
    
    /**
     * 从浏览器中获取cookies (需要用户手动复制)
     */
    public CookiesResult getCookiesFromBrowser() {
        return CookiesResult.instruction(
            "请按以下步骤获取头条号cookies:\n" +
            "1. 在浏览器中打开 https://mp.toutiao.com/ 并登录\n" +
            "2. 登录成功后，按F12打开开发者工具\n" +
            "3. 切换到Network（网络）标签\n" +
            "4. 刷新页面\n" +
            "5. 在请求列表中找到任意一个请求，查看Request Headers\n" +
            "6. 复制Cookie字段的值\n" +
            "7. 将复制的Cookie值粘贴到下面的输入框中"
        );
    }
    
    /**
     * 从响应中提取cookies
     */
    private String extractCookiesFromResponse(Response response) {
        StringBuilder cookiesBuilder = new StringBuilder();
        
        for (String cookie : response.headers("Set-Cookie")) {
            if (cookiesBuilder.length() > 0) {
                cookiesBuilder.append("; ");
            }
            
            // 提取cookie名称和值（忽略path、domain等属性）
            String[] parts = cookie.split(";");
            if (parts.length > 0) {
                cookiesBuilder.append(parts[0].trim());
            }
        }
        
        return cookiesBuilder.toString();
    }
    
    /**
     * 从响应内容中提取用户信息
     */
    private String extractUserInfo(String responseBody) {
        try {
            // 尝试从页面中提取用户信息
            Pattern userInfoPattern = Pattern.compile("userInfo[\"':]\\s*({[^}]+})");
            Matcher matcher = userInfoPattern.matcher(responseBody);
            
            if (matcher.find()) {
                return matcher.group(1);
            }
            
            // 尝试其他可能的用户信息格式
            Pattern userIdPattern = Pattern.compile("user_id[\"':]\\s*[\"']?([^\"',\\s]+)");
            Matcher userIdMatcher = userIdPattern.matcher(responseBody);
            
            if (userIdMatcher.find()) {
                JSONObject userInfo = new JSONObject();
                userInfo.put("user_id", userIdMatcher.group(1));
                return userInfo.toJSONString();
            }
            
        } catch (Exception e) {
            log.warn("提取用户信息失败", e);
        }
        
        return null;
    }
    
    /**
     * Cookies获取结果类
     */
    public static class CookiesResult {
        private boolean success;
        private String cookies;
        private String userInfo;
        private String message;
        private String instruction;
        private LocalDateTime obtainedAt;
        
        private CookiesResult(boolean success, String message) {
            this.success = success;
            this.message = message;
            this.obtainedAt = LocalDateTime.now();
        }
        
        public static CookiesResult success(String cookies, String userInfo) {
            CookiesResult result = new CookiesResult(true, "Cookies获取成功");
            result.cookies = cookies;
            result.userInfo = userInfo;
            return result;
        }
        
        public static CookiesResult notLoggedIn(String message) {
            return new CookiesResult(false, message);
        }
        
        public static CookiesResult error(String message) {
            return new CookiesResult(false, message);
        }
        
        public static CookiesResult instruction(String instruction) {
            CookiesResult result = new CookiesResult(false, "需要手动获取cookies");
            result.instruction = instruction;
            return result;
        }
        
        // Getters
        public boolean isSuccess() { return success; }
        public String getCookies() { return cookies; }
        public String getUserInfo() { return userInfo; }
        public String getMessage() { return message; }
        public String getInstruction() { return instruction; }
        public LocalDateTime getObtainedAt() { return obtainedAt; }
    }
    
    /**
     * Cookies验证结果类
     */
    public static class CookiesValidationResult {
        private boolean valid;
        private boolean success;
        private String message;
        private JSONObject userInfo;
        
        private CookiesValidationResult(boolean success, boolean valid, String message) {
            this.success = success;
            this.valid = valid;
            this.message = message;
        }
        
        public static CookiesValidationResult success(JSONObject userInfo) {
            CookiesValidationResult result = new CookiesValidationResult(true, true, "验证成功");
            result.userInfo = userInfo;
            return result;
        }
        
        public static CookiesValidationResult invalid(String message) {
            return new CookiesValidationResult(true, false, message);
        }
        
        public static CookiesValidationResult error(String message) {
            return new CookiesValidationResult(false, false, message);
        }
        
        // Getters
        public boolean isSuccess() { return success; }
        public boolean isValid() { return valid; }
        public String getMessage() { return message; }
        public JSONObject getUserInfo() { return userInfo; }
    }
}